﻿using System;
using BlobNet.Base.Collections;
using BlobNet.Base.Enums;
using BlobNet.Base.Interfaces;

namespace BlobNet.Base.Common
{
    internal static class TypesHelper
    {
        public static Type GetGenericType(Type sourceType, Type destinationWrapper)
        {
            if (!sourceType.IsGenericType)
                throw new InvalidOperationException("sourceType is not generic");

            Type[] genericArguments;
            return GetGenericType(sourceType, destinationWrapper, out genericArguments);
        }

        public static Type GetGenericType(Type sourceType, Type destinationWrapper, out Type[] genericArguments)
        {
            if (!sourceType.IsGenericType)
                throw new InvalidOperationException("sourceType is not generic");

            genericArguments = sourceType.GetGenericArguments();
            return destinationWrapper.MakeGenericType(genericArguments);
        }

        public static PropertyValueType GetPropertyValueType(object value)
        {
            PropertyValueType result=PropertyValueType.NotSupported;
            if (value != null)
            {
                Type type = value.GetType();

                result = GetPropertyValueType(type);
            }
            //else
            //{
            //    result = PropertyValueType.WrappedObject;
            //}
            return result;
        }

        public static PropertyValueType GetPropertyValueType(Type type)
        {
            PropertyValueType result = PropertyValueType.NotSupported;

            //From the most used to the less used
            if (type.IsEnum)
                result = PropertyValueType.Enumeration;
            else if (type.IsValueType || type == typeof (string))
                result = PropertyValueType.Value;
            else if (typeof (BlobPart).IsAssignableFrom(type))
                result = PropertyValueType.Entity;
            else if (type.IsArray && type.HasElementType && type.GetElementType().IsValueType)
                result = PropertyValueType.Value;
            return result;
        }
    }
}